package com.vclee.fast.integration.imserver;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.vclee.fast.utils.SpringContextUtils;


public class ImServer {
    private static final Logger logger = LoggerFactory.getLogger(ImServer.class);

    private final int serverPort;

    public ImServer(int serverPort) {
        this.serverPort = serverPort;
    }

    public void start() {
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(SpringContextUtils.getBean(ImChannelInitializer.class));
            Channel channel = serverBootstrap.bind(serverPort).sync().channel();
            logger.info("=============Netty服务器启动成功,监听端口为:{}。=================", serverPort);
            channel.closeFuture().sync();
        } catch (Exception e) {
            logger.error("netty服务器启动异常,异常信息为:{}", e.getMessage());
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }
}
